//
//  ICMRepairPartsListViewController.m
//  ICrEAM
//
//  Created by xphone on 16/11/24.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ICMRepairPartsListViewController.h"
#import "ICMHeaderView.h"
#import "ICMRepairPartsCell.h"
#import "ICMRepairPartsModel.h"

@interface ICMRepairPartsListViewController ()<ICMHeaderViewDelegate,UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) ICMHeaderView *headerView;
@property (nonatomic, strong) UIView *listHeaderView;
@property (nonatomic, strong) UITableView *listTableView;
@property (nonatomic, strong) UITextField * searchText;
//data
@property (nonatomic, strong) NSMutableArray *searchArray;
//上拉加载
@property (nonatomic, assign) BOOL hasNext;
@property (nonatomic, assign) int pageNo;

@end

@implementation ICMRepairPartsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BackgroundColor_HeaderBlue;
    [self.view addSubview:self.listHeaderView];
    [self.view addSubview:self.listTableView];
    [self setupListTableView];
    [self setupHeadView];
    [self setupSearchView];
    //上拉加载
    [self setRefresh];
}

#pragma mark 添加上拉加载
- (void)setRefresh {
    __weak ICMRepairPartsListViewController *my = self;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (self.hasNext) {
            self.pageNo++;
            [my getListData:self.searchText.text];
        } else {
            [self.listTableView.mj_footer endRefreshingWithNoMoreData];
        }
    }];
    
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    [footer setTitle:@"正在加载" forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多数据了" forState:MJRefreshStateNoMoreData];
    self.listTableView.mj_footer = footer;
}

#pragma mark 配置tableview
- (void)setupListTableView
{
    self.listTableView.dataSource = self;
    self.listTableView.delegate = self;
    self.listTableView.showsVerticalScrollIndicator = NO;
    self.listTableView.showsHorizontalScrollIndicator = NO;
    [self.listTableView registerClass:[ICMRepairPartsCell class] forCellReuseIdentifier:@"ICMRepairPartsCell"];
    
    self.listTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
}

#pragma mark 配置headView
- (void)setupHeadView
{
    self.headerView = [ICMHeaderView createHeaderViewWithFrame:CGRectMake(ScreenWidth/8, 0, ScreenWidth-(ScreenWidth/8), 40) andTitles:@[@"维修零件查询"] andType:@"1"];
    self.headerView.delegate = self;
    [self.view addSubview:self.headerView];
}

#pragma mark 配置搜索框
- (void)setupSearchView
{
    //搜索框
    UIView *searchView = [[UIView alloc]initWithFrame:CGRectMake(ScreenWidth-ActualWidth(340), ActualHeight(4), ActualWidth(300), ActualHeight(32))];
    
    searchView.backgroundColor = [UIColor whiteColor];
    searchView.layer.cornerRadius = ActualHeight(32)/2.0;
    
    UIImageView *searchImage = [[UIImageView alloc]initWithFrame:CGRectMake(ActualWidth(4), ActualHeight(2), ActualWidth(28), ActualHeight(28))];
    
    searchImage.image = [UIImage imageNamed:GetCar_SearchIcon];
    
    [searchView addSubview:searchImage];
    
    UITextField * searchText = [[UITextField alloc]initWithFrame:CGRectMake(ActualWidth(32), 0, ActualWidth(260)-ActualWidth(32), ActualHeight(32))];
    searchText.placeholder = @"零件代码、零件名称、库位";
    searchText.delegate = self;
    searchText.returnKeyType = UIReturnKeySearch;
    searchText.font = [UIFont systemFontOfSize:14];
    [searchView addSubview:searchText];
    self.searchText = searchText;
    
    [self.view addSubview:searchView];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) name:@"UITextFieldTextDidChangeNotification" object:self.searchText];
}

#pragma mark 搜索框默认支持大写
- (void)textFiledEditChanged:(NSNotification *)obj {
    UITextField *textField = obj.object;
    NSString *toBeString = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            textField.text= toBeString.uppercaseString;
        }else{
            // 有高亮选择的字符串
        }
    }else {
        textField.text = textField.text.uppercaseString;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.searchArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ICMRepairPartsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ICMRepairPartsCell"];
    if (!cell) {
        cell = [[ICMRepairPartsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ICMRepairPartsCell"];
    }
    ICMRepairPartsModel *model = [self.searchArray objectAtIndex:indexPath.row];
    cell.model = model;
    cell.backgroundColor = BackgroundColor_White;
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 2)];
    view.backgroundColor = [UIColor whiteColor];
    [cell addSubview:view];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return ActualHeight(88);
}


- (UITableView *)listTableView
{
    if(!_listTableView)
    {
        _listTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40+ActualHeight(48), ScreenWidth, ScreenHeight-ActualHeight(140)) style:UITableViewStylePlain];
    }
    return _listTableView;
}

- (UIView *)listHeaderView
{
    if(!_listHeaderView)
    {
        _listHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, ActualHeight(40), ScreenWidth, ActualHeight(48))];
        UILabel *firstLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, ActualHeight(20), ActualWidth(224), ActualHeight(20))];
        firstLabel.textColor = ContentTextColor_Gray;
        firstLabel.textAlignment = NSTextAlignmentCenter;
        firstLabel.font = NaviFont;
        firstLabel.text = @"名称/代码";
        [_listHeaderView addSubview:firstLabel];
        firstLabel.centerY = ActualHeight(48)/2;
        
        UILabel *secondLabel = [[UILabel alloc] initWithFrame:CGRectMake(firstLabel.rightEdge, ActualHeight(20), ActualWidth(130), ActualHeight(20))];
        secondLabel.textColor = ContentTextColor_Gray;
        secondLabel.textAlignment = NSTextAlignmentCenter;
        secondLabel.font = NaviFont;
        secondLabel.text = @"零件属性";
        [_listHeaderView addSubview:secondLabel];
        secondLabel.centerY = ActualHeight(48)/2;
        
        UILabel *thirdLabel = [[UILabel alloc] initWithFrame:CGRectMake(secondLabel.rightEdge, ActualHeight(20), ActualWidth(235), ActualHeight(20))];
        thirdLabel.textColor = ContentTextColor_Gray;
        thirdLabel.textAlignment = NSTextAlignmentCenter;
        thirdLabel.font = NaviFont;
        thirdLabel.text = @"库位";
        [_listHeaderView addSubview:thirdLabel];
        thirdLabel.centerY = ActualHeight(48)/2;
        
        UILabel *fourthLabel = [[UILabel alloc] initWithFrame:CGRectMake(thirdLabel.rightEdge, ActualHeight(20), ActualWidth(135), ActualHeight(20))];
        fourthLabel.textColor = ContentTextColor_Gray;
        fourthLabel.textAlignment = NSTextAlignmentCenter;
        fourthLabel.font = NaviFont;
        fourthLabel.text = @"账面库存";
        [_listHeaderView addSubview:fourthLabel];
        fourthLabel.centerY = ActualHeight(48)/2;
        
        UILabel *fifthLabel = [[UILabel alloc] initWithFrame:CGRectMake(fourthLabel.rightEdge, ActualHeight(20), ActualWidth(140), ActualHeight(20))];
        fifthLabel.textColor = ContentTextColor_Gray;
        fifthLabel.textAlignment = NSTextAlignmentCenter;
        fifthLabel.font = NaviFont;
        fifthLabel.text = @"可用库存";
        [_listHeaderView addSubview:fifthLabel];
        fifthLabel.centerY = ActualHeight(48)/2;
        
        UILabel *sixthLabel = [[UILabel alloc] initWithFrame:CGRectMake(fifthLabel.rightEdge, ActualHeight(20), ActualWidth(160), ActualHeight(20))];
        sixthLabel.textColor = ContentTextColor_Gray;
        sixthLabel.textAlignment = NSTextAlignmentCenter;
        sixthLabel.font = NaviFont;
        sixthLabel.text = @"销售价格";
        [_listHeaderView addSubview:sixthLabel];
        sixthLabel.centerY = ActualHeight(48)/2;
        
        //分割线
        UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(firstLabel.rightEdge, 0, 1, ActualHeight(48))];
        line1.backgroundColor = SepColor_gray;
        [_listHeaderView addSubview:line1];
        
        UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(secondLabel.rightEdge, 0, 1, ActualHeight(48))];
        line2.backgroundColor = SepColor_gray;
        [_listHeaderView addSubview:line2];
        
        UIView *line3 = [[UIView alloc] initWithFrame:CGRectMake(thirdLabel.rightEdge, 0, 1, ActualHeight(48))];
        line3.backgroundColor = SepColor_gray;
        [_listHeaderView addSubview:line3];
        
        UIView *line4 = [[UIView alloc] initWithFrame:CGRectMake(fourthLabel.rightEdge, 0, 1, ActualHeight(48))];
        line4.backgroundColor = SepColor_gray;
        [_listHeaderView addSubview:line4];
        
        UIView *line5 = [[UIView alloc] initWithFrame:CGRectMake(fifthLabel.rightEdge, 0, 1, ActualHeight(48))];
        line5.backgroundColor = SepColor_gray;
        [_listHeaderView addSubview:line5];
        
        UIView *line6 = [[UIView alloc] initWithFrame:CGRectMake(0, ActualHeight(48)-1, ScreenWidth, 1)];
        line6.backgroundColor = BackgroundColor_Tanslucent_black;
        [_listHeaderView addSubview:line6];

    }
    _listHeaderView.backgroundColor = [UIColor whiteColor];
    return _listHeaderView;
}

- (NSMutableArray *)searchArray
{
    if(!_searchArray)
    {
        _searchArray = [[NSMutableArray alloc] init];
    }
    return _searchArray;
}

#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //重新搜索要初始化一些变量
    [self.searchArray removeAllObjects];
    self.pageNo = 1;
    [textField resignFirstResponder];
    [self getListData:textField.text];
    return YES;
}

#pragma mark 调接口 获取列表数据
- (void)getListData:(NSString *)text
{
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:text forKey:@"KEY_WORD"];
    [parameters setObject:@(self.pageNo) forKey:@"CURRENT_PAGE"];
    [manager startGetRequestWithURL:QueryPartStock parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if ([data[@"CODE"] integerValue] == 200) {
            if (IsArr(data[@"TM_PART_STOCK"])) {
                NSArray *dataArray = data[@"TM_PART_STOCK"];
                if (dataArray.count != 0 && dataArray) {
                    if(self.pageNo == 1)
                    {
                        [self.searchArray removeAllObjects];
                    }
                    self.listTableView.mj_footer.hidden = NO;
                    for (NSDictionary *searchData in dataArray) {
                        ICMRepairPartsModel *model = [ICMRepairPartsModel yy_modelWithDictionary:searchData];
                        [self.searchArray addObject:model];
                    }
                    self.hasNext = YES;
                    [self.listTableView.mj_footer endRefreshing];
                } else {
                    if (self.searchArray.count == 0) {
                        self.listTableView.mj_footer.hidden = YES;
                        [self.view showString:@"暂无相关搜索结果！" forSeconds:1.5];
                    } else {
                        self.hasNext = NO;
                        [self.listTableView.mj_footer endRefreshingWithNoMoreData];
                    }
                }
            } else {
                if (self.searchArray.count == 0) {
                    self.listTableView.mj_footer.hidden = YES;
                    [self.view showString:@"暂无相关搜索结果！" forSeconds:1.5];
                } else {
                    self.hasNext = NO;
                    [self.listTableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            
            [self.listTableView reloadData];
        } else {
            [self.listTableView.mj_footer endRefreshing];
        }
    }];
}

@end
